<?php

namespace App\Model;

use App\Think\Db;

/**
 * 交易模型
 */
class Trade extends BaseModel
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 交易列表
     * @param  integer $where 
     * @param  integer $page  
     */
    public static function log_list($where=1, $page=1){
        return Db::name('trade')->where($where)->page("{$page},10")->order("id DESC")->cache(60)->select(); 
    }

    /**
     * 充值
     * @param  string $param[money] 
     * @param  string $param[user_id] 
     * @param  string $param[account] 
     * @param  string $param[paytype] 
     * @param  string $param[memo] 
     */
    public static function recharge($param){
        list($time,$money) = [time(),$param['money']];
        $order_sn = isset($param['order_sn']) ? $param['order_sn'] : order_sn();
        $out_trade_no = isset($param['out_trade_no']) ? $param['out_trade_no'] : '';
        Db::startTrans();
        try {
            Db::name('trade_recharge')->insert([
                'user_id' => $param['user_id'],
                'account' => isset($param['account']) ? $param['account'] : '',
                'money'   => $money,
                'paytype' => $param['paytype'],
                'memo'    => isset($param['memo']) ? $param['memo'] : '',
                'ip'      => request()->ip(),
                'order_sn'=> $order_sn,
                'out_trade_no'=> $out_trade_no,
                'createtime' => $time
            ]);
            Db::name('trade')->insert(['user_id'=>$param['user_id'], 'money'=>$money, 'order_sn'=> $order_sn, 'type'=>'recharge', 'memo'=>'余额充值', 'createtime'=>$time]);
            Db::commit();
            return $order_sn;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 提现
     * @param  string $param[money] 
     * @param  string $param[user_id] 
     * @param  string $param[account] 
     * @param  string $param[bank_name] 
     * @param  string $param[bank_no] 
     * @param  string $param[card_type] 
     * @param  string $param[memo] 
     */
    public static function cashout($param){
        list($time,$money,$user_id) = [time(),$param['money'],$param['user_id']];
        $order_sn = isset($param['order_sn']) ? $param['order_sn'] : order_sn();
        Db::startTrans();
        try {
            //冻结余额
            Db::name('user')->where("id='{$user_id}'")->update([ 'money' => Db::raw("money-{$money}"), 'money_freeze' => Db::raw("money_freeze+{$money}") ]);
            //提现流水
            $threshold_info = Db::name('stats_user')->where("user_id='{$user_id}'")->find();
            //记录日志
            Db::name('trade_cashout')->insert([
                'user_id'        => $user_id,
                'order_sn'       => $order_sn,
                'money'          => $money,
                'account'        => $param['account'],
                'bank_name'      => $param['bank_name'],
                'bank_no'        => $param['bank_no'],
                'card_type'      => $param['card_type'],
                'memo'           => isset($param['memo']) ? $param['memo'] : '',
                'threshold_info' => json_encode($threshold_info),
                'createtime'     => $time
            ]);
            Db::name('trade')->insert(['user_id'=>$user_id, 'order_sn'=> $order_sn, 'money'=>-$money, 'type'=>'cashout', 'memo'=>'提现申请', 'createtime'=>$time]);
            Db::commit();
            return $order_sn;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 转账
     * @param  string $param[money] 
     * @param  string $param[user_id] 
     * @param  string $param[from] 
     * @param  string $param[to] 
     * @param  string $param[memo] 
     */
    public static function transfer($param){
        list($time,$money) = [time(),$param['money']];
        $order_sn = isset($param['order_sn']) ? $param['order_sn'] : order_sn();
        $status   = isset($param['status']) ? $param['status'] : 0;
        $memo = isset($param['memo']) ? $param['memo'] : '';
        Db::startTrans();
        try {
            Db::name('trade_transfer')->insert([
                'user_id'  => $param['user_id'],
                'order_sn' => $order_sn,
                'type'     => 'single',
                'money'    => $money,
                'from'     => $param['from'],
                'to'       => $param['to'],
                'status'   => $status,
                'memo'     => $memo,
                'createtime' => $time
            ]);
            Db::name('trade')->insert(['user_id'=>$param['user_id'], 'order_sn'=> $order_sn, 'money'=>+$money, 'type'=>'transfer', 'status'=>$status, 'memo'=>$memo, 'createtime'=>$time]);
            Db::name('user')->where("id='{$param['user_id']}'")->update(['money' => Db::raw("money+{$money}")]);
            Db::commit();
            return $order_sn;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 红利
     * @param  string $param[bonus_type] 
     * @param  string $param[money] 
     * @param  string $param[user_id] 
     * @param  string $param[memo] 
     */
    public static function bonus($param){
        list($time,$money,$user_id) = [time(),$param['money'],$param['user_id']];
        $bonus_type = isset($param['bonus_type']) ? $param['bonus_type'] : '';
        $order_sn   = isset($param['order_sn']) ? $param['order_sn'] : order_sn();
        $status     = isset($param['status']) ? $param['status'] : 1;
        $memo       = isset($param['memo']) ? $param['memo'] : '';
        if($money == 0) return false;

        //所需流水倍数
        $multiple = isset($param['multiple']) ? $param['multiple'] : 1;
        $threshold = $money*$multiple;
        Db::startTrans();
        try {
            //记录日志
            Db::name('trade_bonus')->insert([
                'order_sn'   => $order_sn,
                'bonus_type' => $bonus_type,
                'money'      => $money,
                'user_id'    => $user_id,
                // 'level_id'   => @$param['level_id'],
                //提现门槛相关
                'multiple'   => $multiple,
                'threshold'  => $threshold,

                'ext_json'   => @json_encode($param['ext_json']),
                'memo'       => $memo,
                'createtime' => $time
            ]);
            Db::name('trade')->insert(['user_id'=>$user_id, 'order_sn'=> $order_sn, 'money'=>$money, 'type'=>'bonus', 'memo'=>$memo, 'status'=>$status, 'createtime'=>$time]);
            Db::name('user')->where("id='{$user_id}'")->update(['money' => Db::raw("money+{$money}")]);
            Db::commit();
            return $order_sn;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 处理交易状态
     * @param  string $type  交易类型:cashout=提现,recharge=充值,transfer=转账
     * @param  string $param[order_sn] 
     * @param  string $param[status] 
     * @param  string $param[memo] 可选
     * @param  string $param[trade_memo] 可选
     */
    public static function trade_handle($type='cashout', $param){
        if(!in_array($type, ['recharge','cashout','transfer'])) return false;
        list($order_sn, $status, $now) = [$param['order_sn'], $param['status'], time()];
        $exec = false;
        //金额处理
        $trade_info = Db::name('trade')->where("order_sn='{$order_sn}'")->find();
        if(!$trade_info) return false;
        list($money, $user_id, $trade_status) = [$trade_info['money'], $trade_info['user_id'], $trade_info['status']];
        if($type == 'recharge' && @$status == 1 && $trade_status != 1){
            $exec = Db::name('user')->where("id='{$user_id}'")->update(['money' => Db::raw("money+{$money}")]);
            //提高门槛值
            Db::name('stats_user')->where("user_id='{$user_id}'")->update(['ts_default' => Db::raw("ts_default+{$money}")]);
        }
        if($type == 'cashout' && @$status == 1 && $trade_status != 1){
            $exec = Db::name('user')->where("id='{$user_id}'")->update([ 'money_freeze' => Db::raw("money_freeze+{$money}") ]);
        }
        if($type == 'transfer' && @$status == 1 && $trade_status != 1){
            $exec = Db::name('user')->where("id='{$user_id}'")->update([ 'money' => Db::raw("money+{$money}") ]);
        }

        //更新记录
        $res = Db::name('trade_'.$type)->where("order_sn='{$order_sn}'")->update([
            'status'     => $status,
            'updatetime' => $now
        ]);
        if(!$res || !$exec) return false;
        $res = Db::name('trade')->where("order_sn='{$order_sn}'")->update([
            'status'     => $status,
            'updatetime' => $now
        ]);
        return Db::name('trade')->where("order_sn='{$order_sn}'")->find();
    }



}
